package com.luobi.rabbitmq.producer;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;

import static com.luobi.rabbitmq.constants.TraceIdConstants.CONTEXT_TRACE_ID;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/rabbitmq-producer")
public class RabbitProducer {

    // 注入 RabbitTemplate 工具类
    private final RabbitTemplate rabbitTemplate;

    @GetMapping("/message")
    public String sendMessage(@RequestParam String content) {
        log.info("全局 trace id : {}", MDC.get(CONTEXT_TRACE_ID));

        HashMap<String, Object> messageMap = new HashMap<>();
        messageMap.put("messageId", MDC.get(CONTEXT_TRACE_ID));
        messageMap.put("messageContent", content);  // 消息主题内容
        messageMap.put("sendTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        /*
         * 发送消息
         * 参数1：交换机名称
         * 参数2：路由 routeKey
         * 参数3：消息主题内容
         */
        rabbitTemplate.convertAndSend("boot_topic_exchange", "rabbitmqLearning", messageMap);
        log.info("消息已成功发送，消息主题内容：{}", messageMap);
        return "<p style=color:blue;text-align:center;top:20px;font-size:28px;>来自客户端的消息已发送</p>";
    }

    @GetMapping("/download")
    public String downloadExcel(@RequestParam String fileNo) {
        log.info("全局 trace id : {}", MDC.get(CONTEXT_TRACE_ID));

        HashMap<String, Object> messageMap = new HashMap<>();
        // 消息主题内容
        messageMap.put("fileNo", fileNo);
        messageMap.put("content", String.format("下载文件 : fileNo = {%s}", fileNo));
        messageMap.put("sendTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        /*
         * 发送消息
         * 参数1：交换机名称
         * 参数2：路由 routeKey
         * 参数3：消息主题内容
         */
        rabbitTemplate.convertAndSend("boot_topic_exchange", "rabbitmqLearning", messageMap);
        log.info("请求下载文件的消息已成功发送，消息主题内容：{}", messageMap);
        return "success";
    }

}
